package edu.br.main;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.example.gym4all.R;

import edu.br.activitys.TrainingTypePage;
import edu.br.domain.Training;
import edu.br.domain.TrainingPlan;
import edu.br.enuns.Tag;

public class MainActivity extends Activity {

	private TrainingPlan trainingPlan;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_main);
		this.setTrainingPlan(new TrainingPlan());
		Button button = (Button) this.findViewById(R.id.newTraining);
		List<Training> training = new ArrayList<Training>();
		ArrayAdapter<Training> trainingList = new ArrayAdapter<Training>(this,
				android.R.layout.simple_list_item_1, training);
		trainingList.setNotifyOnChange(true);
		ListView listView = (ListView) this.findViewById(R.id.trainingList);
		listView.setAdapter(trainingList);
		button.setOnClickListener(new ButtonNewTraining(trainingList));

		listView.setOnItemClickListener(new ChooseTrainingType());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		this.getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	public TrainingPlan getTrainingPlan() {
		return this.trainingPlan;
	}

	public void setTrainingPlan(TrainingPlan trainingPlan) {
		this.trainingPlan = trainingPlan;
	}

	private class ButtonNewTraining implements OnClickListener {

		ArrayAdapter<Training> trainingList;

		public ButtonNewTraining(ArrayAdapter<Training> trainingList) {
			this.trainingList = trainingList;
		}

		@Override
		public void onClick(View v) {
			Tag tag = MainActivity.this.getTrainingPlan().nextTag();
			if (tag != null) {
				Training training = new Training(tag);
				MainActivity.this.getTrainingPlan().setLastTag(tag);
				this.trainingList.add(training);
				this.trainingList.notifyDataSetChanged();
			}
		}
	}

	private class ChooseTrainingType implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			Intent intent = new Intent(MainActivity.this,
					TrainingTypePage.class);
			// intent.putExtra("training", arg0);
			MainActivity.this.startActivity(intent);

		}
	}
}
